package service

import (
	"github.com/mojocn/base64Captcha"
	"image/color"
	"math/rand"
	"time"
)

// Captcha 中间件管理服务
var Captcha = new(captchaService)

func init() {
	//init rand seed
	rand.Seed(time.Now().UnixNano())
	// captcha
	Captcha.Store = base64Captcha.NewMemoryStore(1024, 10*time.Minute)
	Captcha.Driver = base64Captcha.NewDriverString(
		150,
		300,
		0,
		0,
		4,
		"%#=qwe23456789rtyupasdfghjkzxcvbnm",
		&color.RGBA{0, 0, 0, 0},
		nil,
		[]string{},
	)
}

// captchaService captcha basic information.
type captchaService struct {
	Driver *base64Captcha.DriverString
	Store  base64Captcha.Store
}

// GenerateIdAndImage 生成一组验证码
func (c *captchaService) GenerateIdAndImage() (string, string, string, error) {
	id, content, answer := c.Driver.GenerateIdQuestionAnswer()
	item, err := c.Driver.DrawCaptcha(content)
	if err != nil {
		return "", "", "", err
	}
	err = c.Store.Set(id, answer)
	if err != nil {
		return "", "", "", err
	}
	b64s := item.EncodeB64string()
	return id, b64s, answer, nil
}

// VerifyIdAndAns 验证Id和answer
func (c *captchaService) VerifyIdAndAns(id, ans string) bool {
	return c.Store.Verify(id, ans, true)
}
